package com.manolo.event.dispatcher;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import com.manolo.event.ChatEvent;
import com.manolo.event.GameStartEvent;
import com.manolo.event.SystemEvent;
import com.manolo.event.listener.ChatListener;
import com.manolo.event.listener.GameListener;
import com.manolo.event.listener.SystemListener;

public class GameDispatcher {
	private static GameDispatcher instance;
	private List<GameListener> externalListeners;
	private List<GameListener> localListeners;

	private GameDispatcher() {
		this.externalListeners = new ArrayList<GameListener>();
		this.localListeners = new ArrayList<GameListener>();
	}

	public synchronized static GameDispatcher getInstance() {
		if(GameDispatcher.instance == null) {
			GameDispatcher.instance = new GameDispatcher();
		}

		return GameDispatcher.instance;
	}

	public void addExternalListener(GameListener listener) {
		this.externalListeners.add(listener);
	}
	
	public void addLocalListener(GameListener listener) {
		this.localListeners.add(listener);
	}

	public void removeExternalListener(GameListener listener) {
		this.externalListeners.remove(listener);
	}
	
	public void removeLocalListener(GameListener listener) {
		this.externalListeners.remove(listener);
	}
	
	public void dispatchGameStartEvent(GameStartEvent event, DispatchType type) {
		List<GameListener> copyList;
		Iterator<GameListener> listener;
		
		switch (type) {
			case EXTERNAL:
				copyList = new ArrayList<GameListener>(this.externalListeners);
				Collections.copy(copyList, this.externalListeners);
				listener = copyList.iterator();
				while( listener.hasNext() ) {
					((GameListener) listener.next()).startGame(event);
				}
				break;
			case LOCAL:
				copyList = new ArrayList<GameListener>(this.localListeners);
				Collections.copy(copyList, this.localListeners);
				listener = copyList.iterator();
				while( listener.hasNext() ) {
					((GameListener) listener.next()).startGame(event);
				}
				break;
		}
	}
}
